package org.csu.jpetstore_users_backend_pj.controller;

import org.csu.jpetstore_users_backend_pj.entity.Order;
import org.csu.jpetstore_users_backend_pj.mapper.CartMapper;
import org.csu.jpetstore_users_backend_pj.result.CommonResponse;
import org.csu.jpetstore_users_backend_pj.result.ResponseCode;
import org.csu.jpetstore_users_backend_pj.service.CartService;
import org.csu.jpetstore_users_backend_pj.service.InventoryService;
import org.csu.jpetstore_users_backend_pj.service.OrderService;
import org.csu.jpetstore_users_backend_pj.util.ThreadLocalUtil;
import org.csu.jpetstore_users_backend_pj.vo.CartVO;
import org.csu.jpetstore_users_backend_pj.vo.OrderVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping
@CrossOrigin(origins = "http://localhost:5173")
public class OrderController {
    @Autowired
    private InventoryService inventoryService;
    @Autowired
    private CartService cartService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private CartMapper cartMapper;


    @GetMapping("/orders")
    @ResponseBody
    public CommonResponse viewOrderHistory(@RequestParam("username")String username){
        //获取订单列表
        List<Order> orders=orderService.getOrdersByName(username);

        OrderVO[] orderVOS=new OrderVO[orders.size()];
        for (int i = 0; i < orders.size(); i++) {
            //获取封装后的购物清单
            String cartInfo = orders.get(i).getCartinfo();
            CartVO cartVO = null;
            try {
                cartVO = cartService.getCartByCartInfo(cartInfo);
            } catch (Exception e) {
                //log.error("解析 cartInfo 失败: {}", cartInfo, e);
                cartVO = new CartVO(); // 默认值
            }
            orderVOS[i]=(new OrderVO(orders.get(i),cartVO));
        }
        return CommonResponse.createForSuccess(ResponseCode.GetCartSuccess.getCode(),ResponseCode.GetCartSuccess.getDescription(),orderVOS);
    }

    @PostMapping("/confirmOrder/{username}")
    public CommonResponse confirmOrder(
            @RequestParam("cardType") String cardType,
            @RequestParam("Number") String number,
            @RequestParam("ODate") String Odate,
            @RequestParam("FirstName") String firstName,
            @RequestParam("LastName") String lastName,
            @RequestParam("Address1") String address1,
            @RequestParam("Address2") String address2,
            @RequestParam("City") String city,
            @RequestParam("State") String state,
            @RequestParam("Zip") String zip,
            @RequestParam("Country") String country,
            @RequestParam("EDate") String Edate, @PathVariable String username) {

        CartVO cart = cartService.getCart(username);

        // 1. 遍历购物车，检查库存
        for (var cartItem : cart.getCartItemList()) {
            String itemId = cartItem.getItem().getItemId();
            int quantity = cartItem.getQuantity();

            int stock = inventoryService.getInventoryByItemId(itemId);
            if (stock < quantity) {
                return CommonResponse.createForError(ResponseCode.InventoryShortageSuccess.getCode(),
                        "商品 [" + itemId + "] 库存不足，剩余：" + stock);
            }
        }

        // 2. 扣库存
        for (var cartItem : cart.getCartItemList()) {
            String itemId = cartItem.getItem().getItemId();
            int quantity = cartItem.getQuantity();

            boolean success = inventoryService.decreaseInventory(itemId, quantity);
            if (!success) {
                return CommonResponse.createForError(ResponseCode.InventoryShortageSuccess.getCode(),
                        "商品 [" + itemId + "] 扣库存失败");
            }
        }
        Order newOrder = new Order();
        newOrder.setExprdate(Edate);
        newOrder.setUsername(username);
        newOrder.setType(cardType);
        newOrder.setPhone(number);
        newOrder.setDate(Odate);
        newOrder.setFirstName(firstName);
        newOrder.setLastname(lastName);
        newOrder.setAddress1(address1);
        newOrder.setAddress2(address2);
        newOrder.setCity(city);
        newOrder.setState(state);
        newOrder.setZip(zip);
        newOrder.setCountry(country);
        double Value = cart.getSubTotal().doubleValue();
        newOrder.setPrice(Value);
        newOrder.setCartinfo(cartMapper.selectById(username).getCartinfo());
        orderService.addOrder(newOrder);
        //确认订单之后没有删除对应购物车的商品?


        return CommonResponse.createForSuccess(ResponseCode.ConfirmOrderSuccess.getCode(),ResponseCode.ConfirmOrderSuccess.getDescription(),newOrder);

    }

    @DeleteMapping("/confirmOrder/{username}")
    public CommonResponse HandlerCart(@PathVariable String username) {
        cartService.clearCart(username);
        return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(),ResponseCode.SUCCESS.getDescription());
    }

}
